package top.lingkang.finalgateway.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.noear.snack.ONode;
import top.lingkang.finalgateway.FinalGateway;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lingkang
 * @create by 2024/4/26 16:09
 */
public class StaticMimes {
    public static final Map<String, String> mimeMap = new HashMap<>();

    public static void loadConfig() {
        File file = new File(FinalGateway.dir + File.separator + "conf" + File.separator + "mime.types.json");
        String json = null;
        if (!file.exists()) {
            json = IoUtil.readUtf8(StaticMimes.class.getClassLoader().getResourceAsStream("mime.types.json"));
            FileUtil.writeString(json, file, StandardCharsets.UTF_8);
        }
        if (json == null)
            json = FileUtil.readUtf8String(file);
        ONode node = ONode.loadStr(json);
        node.forEach((s, oNode) -> {
            mimeMap.put(s, oNode.getString());
        });
    }

    /**
     * 添加 Mime 记录
     */
    public synchronized static String add(String extension, String conentType) {
        return mimeMap.put(extension, conentType);
    }

    /**
     * 查找 Mime 记录（找到对应的内容类型）
     */
    public static String get(String ext) {
        return mimeMap.get(ext);
    }

}
